﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace Community.SharePoint.FAST.PowerShell
{
    /// <summary>
    /// SharePoint PowerShell Community Kit
    /// Get-FASTSearchIndexLocation
    /// This cmdlet displays where Microsoft FAST Search Server 2010 for SharePoint stores it's index files.
    /// Author: Mikael Svenson (mikael.svenson@comperiosearch.com / miksvenson@gmail.com)
    /// Creation Date: 1/11/2011
    /// http://techmikael.blogspot.com
    /// </summary>

    [Cmdlet(VerbsCommon.Get, "FASTSearchIndexLocation")]
    public class GetIndexLocation : PSCmdlet
    {
        protected override void ProcessRecord()
        {
            Dictionary<string, string> results = ReadFolderPaths();

            WriteObject(results, true);
        }

        public Dictionary<string, string> ReadFolderPaths()
        {
            string espDir = Environment.GetEnvironmentVariable("FASTSEARCH");
            if (string.IsNullOrEmpty(espDir)) throw new Exception("Cannot locate FASTSEARCH environmental variable");

            string rtsplatformrc = Path.Combine(espDir, @"etc\rtsplatformrc.xml");
            XDocument rtDoc = XDocument.Load(rtsplatformrc);
            var folders = from element in rtDoc.Descendants("common")
                          select
                              new
                                  {
                                      IndexDir = element.Attribute("indexDir").Value,
                                      FixmlDir = element.Attribute("fixmlDir").Value
                                  };

            Dictionary<string, string> results = new Dictionary<string, string>();

            string indexDir = DirectoryHelper.GetSymbolicLinkTarget(folders.First().IndexDir);
            string fixmlDir = DirectoryHelper.GetSymbolicLinkTarget(folders.First().FixmlDir);

            results.Add("IndexDir", indexDir);
            results.Add("FixmlDir", fixmlDir);

            foreach (string search in Directory.GetFiles(Path.Combine(espDir, "etc"), "searchrc-*.xml"))
            {
                Match match = Regex.Match(search, @"searchrc-(?<num>\d+)");
                if (!match.Success) continue;
                XDocument searchDoc = XDocument.Load(search);

                var searchFolders = from element in searchDoc.Descendants("common")
                                    select
                                        new { IndexPath = element.Attribute("indexpath").Value };
                string indexPath = DirectoryHelper.GetSymbolicLinkTarget(searchFolders.First().IndexPath);
                results.Add("searchrc-" + match.Groups["num"].Value + " IndexPath", indexPath);
            }
            return results;
        }
    }
}